package com.tjec.project.system.service.impl;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.enums.CodeNum;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.file.FileNetUrl;
import com.tjec.common.utils.poi.ImportExcelUtil;
import com.tjec.framework.security.service.TokenService;
import com.tjec.project.businessWorkbench.domain.BmsBusinessPickup;
import com.tjec.project.system.domain.*;
import com.tjec.project.system.domain.vo.BmsAttachmentVo;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.mapper.BmsCategoryAssociatedMapper;
import com.tjec.project.system.mapper.BmsMdBusinessCategoryMapper;
import com.tjec.project.system.mapper.BmsMdPickupTemplateMapper;
import com.tjec.project.system.mapper.BmsPickupTemplateListMapper;
import com.tjec.project.system.service.IBmsAttachmentService;
import com.tjec.project.system.service.IBmsMdPickupTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 收资模板Service业务层处理
 *
 * @author tjec
 * @date 2020-04-16
 */
@Service
public class BmsMdPickupTemplateServiceImpl implements IBmsMdPickupTemplateService {
    @Autowired
    private BmsMdPickupTemplateMapper bmsMdPickupTemplateMapper;
    @Autowired
    private IBmsAttachmentService iBmsAttachmentService;
    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;
    @Autowired
    private BmsCategoryAssociatedMapper bmsCategoryAssociatedMapper;
    @Autowired
    private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private BmsPickupTemplateListMapper bmsPickupTemplateListMapper;
    /**
     * 查询收资模板
     * 
     * @param guid 收资模板ID
     * @return 收资模板
     */
    @Override
    public BmsMdPickupTemplate selectBmsMdPickupTemplateById(String guid) {
        BmsMdPickupTemplate entity = bmsMdPickupTemplateMapper.selectBmsMdPickupTemplateById(guid);
        if (StringUtils.isNotBlank(entity.getAttachmentId())) {
            entity.setAttachmentList(iBmsAttachmentService.selectBmsAttachmentDownload(entity.getAttachmentId()));
        }
        //业务类型
        List<BmsMdBusinessCategory> bmsMdBusinessCategoryList = bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociated(guid, null);
        entity.setBusinessCategoryList(bmsMdBusinessCategoryList);
        //转化guid成List<String>
        List<String> lists= new ArrayList<String>();
        for (BmsMdBusinessCategory bmsMdBusinessCategory:bmsMdBusinessCategoryList) {
            lists.add(bmsMdBusinessCategory.getGuid()) ;
        }
        entity.setBusinessCategoryIds(lists);
        return entity;
    }

    /**
     * 查询收资模板列表
     * 
     * @param bmsMdPickupTemplate 收资模板
     * @return 收资模板
     */
    @Override
    public List<BmsMdPickupTemplate> selectBmsMdPickupTemplateList(BmsMdPickupTemplate bmsMdPickupTemplate) {
        List<BmsMdPickupTemplate> list = bmsMdPickupTemplateMapper.selectBmsMdPickupTemplateList(bmsMdPickupTemplate);
        list.forEach(item -> {
            if (StringUtils.isNotBlank(item.getAttachmentId())) {
                item.setAttachmentList(iBmsAttachmentService.selectBmsAttachmentDownload(item.getAttachmentId()));
            }
            item.setBusinessCategoryList(bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociated(item.getGuid(),bmsMdPickupTemplate.getBusinessCategoryId()));
        });
        return list;
    }

    /**
     * 新增收资模板
     * 
     * @param bmsMdPickupTemplate 收资模板
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int insertBmsMdPickupTemplate(BmsMdPickupTemplate bmsMdPickupTemplate)
    {
        bmsMdPickupTemplate.setCreateTime(DateUtils.getNowDate());
        int ret = bmsMdPickupTemplateMapper.insertBmsMdPickupTemplate(bmsMdPickupTemplate);
        if (ret > -1) {
            updateAttachment(bmsMdPickupTemplate);
            updateBusinessCategory(bmsMdPickupTemplate);
            
            //插入收资管理清单模板内容
            bmsMdPickupTemplate.setBusinessCategoryId(StringUtils.join(bmsMdPickupTemplate.getBusinessCategoryIds(),","));
            insertBatchPickupList(bmsMdPickupTemplate,"1");
        }
        return ret;
    }
    
    public void insertBatchPickupList(BmsMdPickupTemplate bmsMdPickupTemplate,String flag) {//1:新增，2:修改
    	if(com.tjec.common.utils.StringUtils.isNotBlank(bmsMdPickupTemplate.getAttachmentId())) {
    		//如果是修改，需要判断附件是否变化
    		if("2".equals(flag)) {
    			//获取原来的数据
    			bmsPickupTemplateListMapper.deleteBmsPickupTemplateListByTemplateId(bmsMdPickupTemplate.getGuid());
    		}
    		
    		List<BmsAttachmentVo> attachments = iBmsAttachmentService.selectBmsAttachmentDownload(bmsMdPickupTemplate.getAttachmentId());
    		if (CollectionUtils.isEmpty(attachments)) {
				return;
			}

			StringBuffer sb = new StringBuffer(attachments.get(0).getStoragePath());
			
			File file = null;
			if (attachments.get(0).getStoragePath().startsWith("https://")) {
				file = FileNetUrl.getNetUrlHttps(sb.toString());
			} else {
				file = FileNetUrl.getNetUrlHttp(sb.toString());
			}
			FileInputStream inputStream;
			try {
				inputStream = new FileInputStream(file);
				List<List<Object>> list = ImportExcelUtil.getBankListByExcel(inputStream, "前期咨询-任务管理清单模板文件.xlsx");

				List<BmsPickupTemplateList> bmsPickupTemplateLists = new ArrayList<BmsPickupTemplateList>();
				
				String[] businessTypeIds = StringUtils.split(bmsMdPickupTemplate.getBusinessCategoryId(),",");
				for (String string : businessTypeIds) {
					for (int i = 0; i < list.size(); i++) {
						BmsPickupTemplateList bmsPickupTemplateList = new BmsPickupTemplateList();
						bmsPickupTemplateList.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
						bmsPickupTemplateList.setBusinessTypeId(string);
						bmsPickupTemplateList.setTemplateId(bmsMdPickupTemplate.getGuid());
						for (int j = 0; j < list.get(i).size(); j++) {
							if (j == 0) {
								bmsPickupTemplateList.setPickUpName(list.get(i).get(j).toString());
								bmsPickupTemplateList.setCreateBy(
										tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
							}else if(j == 1) {
								bmsPickupTemplateList.setRemark(list.get(i).get(j).toString());
							}
						}
						
						if(!"".equals(bmsPickupTemplateList.getPickUpName()) && bmsPickupTemplateList.getPickUpName()!=null) {
							bmsPickupTemplateLists.add(bmsPickupTemplateList);
						}
						
					}
				}
				
				bmsPickupTemplateListMapper.insertBmsPickupTemplateLists(bmsPickupTemplateLists);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	
    }

    /**
     * 更新业务类别表
     * @param entity
     */
    private void updateBusinessCategory(BmsMdPickupTemplate entity) {
        if(!CollectionUtils.isEmpty(entity.getBusinessCategoryIds())){
            List<String> categoryList = entity.getBusinessCategoryIds();
            //添加关联库的数据  业务类别的关联
            for (String bms:categoryList) {
                BmsCategoryAssociated associated = new BmsCategoryAssociated();
                associated.setCategoryGuid(bms);
                associated.setParentGuid(entity.getGuid());
                associated.setGuid(UUID.randomUUID().toString());
                associated.setFlag(CodeNum.FOUR.getCode());
                bmsCategoryAssociatedMapper.insertBmsCategoryAssociated(associated);
            }
        }
    }

    /**
     * 新增、修改时更新文件表
     *
     * @param entity
     */
    private void updateAttachment(BmsMdPickupTemplate entity) {
        if(StringUtils.isNotBlank(entity.getAttachmentId())){
            BmsAttachment bmsAttachment = new BmsAttachment();
            bmsAttachment.setGuid(entity.getAttachmentId());
            bmsAttachment.setBizId(entity.getGuid());
            bmsAttachment.setDelFlag(NumCode.ZERO.getCode());
            bmsAttachment.setCategory(AttachmentConstants.BUSINESS_PICKUP);
            iBmsAttachmentService.updateBmsAttachment(bmsAttachment);
        }
    }
    /**
     * 修改收资模板
     * 
     * @param bmsMdPickupTemplate 收资模板
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateBmsMdPickupTemplate(BmsMdPickupTemplate bmsMdPickupTemplate)
    {
        bmsMdPickupTemplate.setUpdateTime(DateUtils.getNowDate());
        int ret =  bmsMdPickupTemplateMapper.updateBmsMdPickupTemplate(bmsMdPickupTemplate);
        if (ret > -1) {
            bmsAttachmentMapper.updateBmsAttachmentByBizId(new String[]{bmsMdPickupTemplate.getGuid()}, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
            updateAttachment(bmsMdPickupTemplate);

            //对业务类别进行修改先删除在重现添加
            bmsCategoryAssociatedMapper.deleteBmsCategoryAssociatedByParentId(bmsMdPickupTemplate.getGuid());
            updateBusinessCategory(bmsMdPickupTemplate);
            
            bmsMdPickupTemplate.setBusinessCategoryId(StringUtils.join(bmsMdPickupTemplate.getBusinessCategoryIds(),","));
            insertBatchPickupList(bmsMdPickupTemplate,"2");
        }
        return ret;
    }

    /**
     * 批量删除收资模板
     * 
     * @param guids 需要删除的收资模板ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdPickupTemplateByIds(String[] guids)
    {
    	bmsPickupTemplateListMapper.deleteBmsPickupTemplateListByTemplateIds(guids);
        return bmsMdPickupTemplateMapper.deleteBmsMdPickupTemplateByIds(guids);
    }

    /**
     * 删除收资模板信息
     * 
     * @param guid 收资模板ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdPickupTemplateById(String guid)
    {
        return bmsMdPickupTemplateMapper.deleteBmsMdPickupTemplateById(guid);
    }
}
